<template>
  <div class="login-container">
    <el-card class="login-card">
      <h2 class="login-title">图书管理系统</h2>
    <el-form :model="loginForm" ref="loginForm" :rules="loginRules" label-width="80px" @submit.native.prevent>
      <el-form-item prop="username" label="用户名">
        <el-input v-model="loginForm.username" placeholder="请输入用户名"></el-input>
      </el-form-item>
      <el-form-item prop="password" label="密码">
        <el-input v-model="loginForm.password" type="password" placeholder="请输入密码"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="login">登录</el-button>
      </el-form-item>
    </el-form>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      loginForm: {
        username: 'admin',
        password: 'admin',
      },
      loginRules: {
        username: [
          { required: true, message: '用户名不能为空', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '密码不能为空', trigger: 'blur' }
        ]
      }
    };
  },
  methods: {
    login() {
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          this.handleLogin();
        } else {
          return false;
        }
      });
    },
    async handleLogin() {
      try {
        const response = await this.$axios.post('/api/auth/login', {
          username: this.loginForm.username,
          password: this.loginForm.password,
        });
        if (response.data.code === 200) {
          //this.$store.dispatch('login');
          this.$store.dispatch('login', response.data.data.accessToken);
          this.$router.push('/books');
        } else {
          this.$message.error(response.data.msg);
        }
      } catch (error) {
        this.$message.error('登录失败，请稍后重试');
      }
    },
  },
};
</script>
<style scoped>
  .login-container {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 100vh;
    background-color: #f4f4f4;
  }

  .login-card {
    width: 350px;
    padding: 20px;
    background-color: white;
    border-radius: 5px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  }

  .login-title {
    text-align: center;
    margin-bottom: 20px;
    font-size: 24px;
    color: #333;
  }
</style>